package com.babylove.project.process.service.impl;

import com.babylove.common.exception.CustomException;
import com.babylove.common.utils.SecurityUtils;
import com.babylove.common.utils.bean.BeanUtils;
import com.babylove.project.process.domain.DeploymentEntity;
import com.babylove.project.process.domain.ProcessDefinitionEntity;
import com.babylove.project.process.domain.vo.WorkFlowVo;
import com.babylove.project.process.service.WorkFlowService;
import com.babylove.project.purchase.domain.resp.TaskEntityResp;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipInputStream;

/**
 * @BelongsProject: babylove
 * @BelongsPackage: com.babylove.project.process.service.impl
 * @Author: caoqingwen
 * @CreateTime: 2020-07-03 21:00
 * @Description: 工作流Service
 */
@Service
public class WorkFlowServiceImpl implements WorkFlowService {

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private HistoryService historyService;

    @Resource
    private TaskService taskService;


    @Override
    public List<DeploymentEntity> getRepositoryList(WorkFlowVo workFlowVo) {
        if (workFlowVo.getDeploymentName() == null) {
            workFlowVo.setDeploymentName("");
        }

        List<Deployment> deploymentList = repositoryService.createDeploymentQuery().
                deploymentNameLike("%" + workFlowVo.getDeploymentName() + "%").list();
        List<DeploymentEntity> returnList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(deploymentList)) {
            deploymentList.stream().forEach(deployment -> {
                DeploymentEntity deploymentEntity = new DeploymentEntity();
                BeanUtils.copyProperties(deployment, deploymentEntity);
                returnList.add(deploymentEntity);
            });
        }
        return returnList;
    }


    @Override
    public List<ProcessDefinitionEntity> getProcessDefinitionList(String processDefinitionId) {
        List<ProcessDefinitionEntity> returnList = new ArrayList<>();
        List<ProcessDefinition> processDefinitionList = repositoryService.createProcessDefinitionQuery().deploymentId(processDefinitionId).list();
        if (CollectionUtils.isNotEmpty(processDefinitionList)) {
            for (ProcessDefinition processDefinition : processDefinitionList) {
                ProcessDefinitionEntity processDefinitionEntity = new ProcessDefinitionEntity();
                BeanUtils.copyProperties(processDefinition, processDefinitionEntity);
                returnList.add(processDefinitionEntity);
            }
        }
        return returnList;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deploymentProcess(MultipartFile file, String deploymentName) {
        InputStream inputStream = null;
        ZipInputStream zipInputStream = null;
        try {
            inputStream = file.getInputStream();
            zipInputStream = new ZipInputStream(inputStream);
            repositoryService.createDeployment().name(deploymentName).addZipInputStream(zipInputStream).deploy();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("部署流程失败");
        } finally {
            try {
                zipInputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


    @Override
    public void deleteDeployment(DeploymentEntity deploymentEntity) {
        repositoryService.deleteDeployment(deploymentEntity.getId(), true);
    }

    @Override
    public InputStream getProcessPic(String id) {
        //根据部署id查询流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(id).singleResult();
        //从流程对象中获取图片名称
        String diagramResourceName = processDefinition.getDiagramResourceName();
        //使用部署id和图片名称去查询图片流
        InputStream stream = repositoryService.getResourceAsStream(id, diagramResourceName);
        return stream;
    }


    /**
     * TODO 后期封装成公共方法
     */
    public void getUserTaskList() {
        String username = SecurityUtils.getUsername();
        List<TaskEntityResp> list = new ArrayList<>();
        List<Task> taskList = taskService.createTaskQuery().taskAssignee(username).list();
        if (CollectionUtils.isNotEmpty(taskList)) {
            taskList.forEach(task -> {
                TaskEntityResp taskEntityResp = new TaskEntityResp();
                list.add(taskEntityResp);
            });
        }


    }

}
